package com.controller;

import com.Util.DB;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.inject.servlet.RequestParameters;
import lombok.extern.slf4j.Slf4j;
import org.jooq.*;
import org.jooq.impl.DSL;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.sql.Connection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.Util.DBUtils.dataChangeJsonObject;
import static com.Util.DBUtils.dataChangeJsonArray;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import static com.controller.WebSocket.*;

@Path ( "hello" )
@Slf4j
public class RestfulHelloWorld extends BaseController {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHelloWorld() {
        return "Hello World!";
    }

    @GET
    @Path("/{param}")
    @Produces("text/plain;charset=UTF-8")
    public String sayHello2UserByText(@PathParam ("param") String username) {
        return "Hello " + username;
    }

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public String sayHelloToUserByJson(@QueryParam ("username") String username) {
       return null;
    }

    /**
     * 根据Id获取用户签到信息
     * @param query {"query": {"userId":63}}
     * @return
     */
   /* @POST
    @Path ( "findByUserId" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    @Consumes(MediaType.APPLICATION_JSON)
    public String getSign(String query){
        try(Connection conn= DB.getConnection ();
            DSLContext create= DSL.using ( conn, SQLDialect.MYSQL )) {
            //创建事务
            //解析参数
            this.jsonObject=new JsonParser ().parse ( query ).getAsJsonObject ().get ( "query" ).getAsJsonObject ();
            //获取userId
            Integer userId=this.jsonObject.get ( "userId" ).getAsInt ();
            Integer currentPage=this.jsonObject.get ( "page" ).getAsInt ();
            Integer pageSize=this.jsonObject.get ( "pagenum" ).getAsInt ();
            //执行查询
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            Date date=new Date (  );
            String dateParam=format.format ( date );
            //正常查询
           *//* Result<Record> records=create.select (  )
                    .from ( SIGN_FROM )
                    .where ( SIGN_FROM.USER_ID.eq ( userId ) )
                    .and ( SIGN_FROM.CREATE_TIME.like ( "%"+dateParam+"%" ) )
                    .limit ( pageSize)
                    .offset ( (currentPage-1)*pageSize )
                    .fetch ();*//*
            //连表查寻
           *//* Result<Record3<Integer,Timestamp,String>> records=create.select ( SIGN_FROM.USER_ID.as ( "id" ),
                    SIGN_FROM.CREATE_TIME.as ( "time" ),
                    MUSIC_USER.NIKE_NAME.as ( "name" ))
                    .from ( SIGN_FROM )
                    .join ( MUSIC_USER )
                    .on ( SIGN_FROM.USER_ID.eq ( MUSIC_USER.ID ))
                    //.where ( SIGN_FROM.USER_ID.eq ( userId ) )
                   // .and ( SIGN_FROM.CREATE_TIME.like ( "%"+dateParam+"%" ) )
                    .orderBy ( SIGN_FROM.CREATE_TIME.desc () )
                    //.limit ( pageSize)
                    //.offset ( (currentPage-1)*pageSize )
                    .fetch ();
            log.info ( "{数据}={}",create.selectQuery () );*//*
            //使用lambda
            Map<String,TestUser> stringListMap=new LinkedHashMap<> (  );
            //Map<String,List<testUser>> stringListMap;
            //lambda实例1
            *//*stringListMap = records
                    .stream ()
                    .collect (
                            groupingBy (
                                    r -> r.getValue ("name", String.class),
                                    LinkedHashMap::new,
                                    mapping(
                                            r->new testUser (
                                                    r.getValue("time", String.class),
                                                    r.getValue("name", String.class)
                                            ),
                                            toList ()
                                    )


                            )

                    );*//*
                //lambda表达式实例2
                stringListMap=records
                        .stream ()
                        .collect (
                                Collectors.toMap (
                                        //创建key
                                //k->k.getValue ( "name",String.class )+","+k.getValue ( "time",String.class ),
                                        k->k.getValue ( "id",String.class ),
                                        //构建value
                                        v->new TestUser (
                                                v.getValue ( "time",String.class ),
                                                v.getValue ( "name",String.class )
                                        ),
                                        (v1,v2)->{
                                            if (false){
                                                return v1;
                                            } else {
                                                return v2;
                                            }
                                        }

                                )

                        );

            log.info ( "【数据信息】={}",stringListMap );
            //this.jsonArray=dataChangeJsonArray (records);
            JsonObject result=new JsonObject ();
            result.add ( "rows",this.jsonArray );
            return success (stringListMap);
        }catch (Exception e){
            return error ( -1,"系统异常" );
        }
    }*/

    /**
     * 测试websocket
     */
    @GET
    @Path ( "test" )
    @Produces(MediaType.APPLICATION_JSON+";charset=utf-8")
    public String  testWebSocket(){
        WebSocket webSocket=new WebSocket ();
        TestUser testUser=new TestUser ( "14234","wer" );
        try {
           webSocket.sendMessage ( testUser );
           log.info ( "【消息已发送】" );
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return success ("ok");
    }

}
